package com.innovation.ic.im.end.base.thread.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.innovation.ic.im.end.base.handler.helper.HandlerHelper;
import com.innovation.ic.im.end.base.pojo.ServiceResult;
import com.innovation.ic.im.end.base.pojo.constant.Constants;
import com.innovation.ic.im.end.base.pojo.im_erp9.AccountGroupLastContactPojo;
import com.innovation.ic.im.end.base.service.helper.ServiceImplHelper;
import com.innovation.ic.im.end.base.thread.AbstractThread;
import java.util.List;

/**
 * 一对一聊天环境下，推送rabbitMq消息
 */
public class SendRabbitMqMessageThread extends AbstractThread implements Runnable {
    private List<String> toUserAccountList;

    private String exchange;

    private int ifHaveNewMsg = 0;

    private String sendMsgUser;

    public SendRabbitMqMessageThread() {
    }

    public SendRabbitMqMessageThread(List<String> toUserAccountList, String exchange) {
        this.toUserAccountList = toUserAccountList;
        this.exchange = exchange;
    }

    /**
     *
     * @param toUserAccountList 接收mq消息的用户列表
     * @param exchange 交换机
     * @param ifHaveNewMsg 是否有新消息
     * @param sendMsgUser 发送消息的用户
     */
    public SendRabbitMqMessageThread(List<String> toUserAccountList, String exchange, int ifHaveNewMsg, String sendMsgUser) {
        this.toUserAccountList = toUserAccountList;
        this.exchange = exchange;
        this.ifHaveNewMsg = ifHaveNewMsg;
        this.sendMsgUser = sendMsgUser;
    }

    @Override
    public void run() {
        if(toUserAccountList != null && toUserAccountList.size() > 0){
            for (int i = 0; i < toUserAccountList.size(); i++) {
                String toUserAccount = toUserAccountList.get(i);
                ServiceResult<List<AccountGroupLastContactPojo>> lastContact = ServiceImplHelper.getUserGroupService().findLastContact(toUserAccount);
                if (lastContact != null && lastContact.getResult() != null) {
                    JSONObject json = (JSONObject) JSONObject.parse(JSON.toJSONString(lastContact));
                    // 判断如果接收消息的人就是发送消息的人说明消息是发送给自己的，表示没有新消息，修改字段值为0
                    if(sendMsgUser != null && toUserAccount.equals(sendMsgUser)){
                        json.put(Constants.IF_HAVE_NEW_MSG_FIELD, 0);
                    }else{
                        json.put(Constants.IF_HAVE_NEW_MSG_FIELD, ifHaveNewMsg);
                    }
                    HandlerHelper.getRabbitMqHandler().sendRabbitMqMsg(toUserAccount, json.toJSONString(), exchange);
                }
            }
        }
    }
}